<template lang="pug">
div
  nav-div
  .ui.grid.bottom.aligned
    .six.wide.column
      h1.ui.header {{product.name}}
    .ten.wide.column.right.aligned
      .ui.button(v-if="['view'].includes(mode)", @click="mode = 'edit'") 编辑
      .ui.button(v-if="['edit'].includes(mode)", @click="save") 保存
      .ui.button.negative(v-if="['edit'].includes(mode)", @click="cancel") 取消
  .ui.divider
  view(
    v-if="['view'].includes(mode)",
    :product="product",
    :selected="selected",
  )
  edit(
    v-if="['edit'].includes(mode)",
    :product.sync="product",
    :selected="selected",
  )
</template>

<script>
import { getProduct, updateProduct } from '../../vuex/action'
import NavDiv from '../../modules/nav'
import View from './view'
import Edit from './edit'

export default {
  name: 'product',
  components: {
    View,
    Edit,
    NavDiv,
  },
  vuex: {
    getters: {
      productSource: ({ product }) => product.product,
    },
    actions: {
      getProduct,
      updateProduct,
    }
  },
  data() {
    return {
      product: null,
      mode: 'view',
      selected: null,
    }
  },
  computed: {
  },
  methods: {
    save () {
      catchError(async () => {
        let data = _.cloneDeep(this.product)
        data.sub_products = _.map(data.sub_products, (item, index) => _.assign(item, {index}))
        await this.updateProduct(data)
        await this.getProduct(data.id)
        this.mode = 'view'
      }, '更新成功')
    },
    cancel () {
      this.mode = 'view'
      this.product = _.cloneDeep(this.productSource)
      this.product.sub_products = _.orderBy(this.product.sub_products, ['index'], ['asc'])
      this.selected = this.product.sub_products[0]
    },
  },
  route: {
    data({ to: { params: { id }, query: { mode } } }) {
      catchError(async () => {
        await this.getProduct(id)
        if (mode) {
          this.mode = mode
        }
      })
    }
  },
  ready() {
    $(this.$el).find('.dropdown').dropdown({
      on: 'hover'
    })
  },
  watch: {
    productSource: {
      handler (val, old) {
        this.helper.title(val.name)
        this.product = _.cloneDeep(val)
        this.product.sub_products = _.orderBy(this.product.sub_products, ['index'], ['asc'])
        this.selected = this.product.sub_products[0]
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>

<style lang="sass" scoped>
</style>
